<template>
  <a-modal v-model:open="open" width="60%" :title="isEdit ? $t('编辑') : $t('New')" @afterClose="handleClose"
    :maskClosable="false">
    <a-spin :spinning="spinning">
      <div class="menus">
        <div class="menus-permission">
          {{ $t("当前菜单") }} {{ currentSelectMenu }}
          <div v-if="currentId">
            <div>
              {{ $t("按钮权限") }}
            </div>
            <!-- :options="menuOptions" -->
            <a-checkbox-group v-model:value="menuSelected" name="checkboxgroup">
              <!-- <template #label="{ labelZh, labelEn, labelAr }"> -->
                <a-row>
                  <a-col :span="6" v-for="(item, index) in menuOptions">
                    <!-- <span v-if="isEn">{{ labelEn }}</span>
                    <span v-if="isCn">{{ labelZh }}</span>
                    <span v-if="isArabic">{{ labelAr }}</span> -->
                    <a-checkbox :value="item.value">{{ isCn ? item.labelZh : isArabic ? item.labelAr :  item.labelEn }}</a-checkbox>
                  </a-col>
                </a-row>
              <!-- </template> -->
            </a-checkbox-group>
          </div>
          <div v-else>
            {{ $t("权限分配提示") }}
          </div>
        </div>
        <!--  -->

        <a-tree class="treeStyle" v-if="treeData.length" :defaultExpandAll="true" v-model:checkedKeys="checkedKeys"
          checkStrictly @check="chooseKey" checkable :tree-data="treeData" :fieldNames="{
            key: 'id',
            children:'children'
          }">
          <template #title="{ nameZh, nameEn, nameAr, id, parentId, path, record }">
            <div style="display: flex; align-items: center"
              @click="setMenuPermission(parentId, id, nameZh, nameEn, nameAr)">
              <span style="font-size: 14px">
                <span v-if="isCn && nameZh">{{ nameZh }}</span>
                <span v-else-if="isArabic && nameAr">{{ nameAr }}</span>
                <span v-else>{{ nameEn }}</span>
              </span>
            </div>
          </template>
        </a-tree>
      </div>

    </a-spin>
    <template #footer>
      <a-button key="back" @click="handleClose">{{ $t("关闭") }}</a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="submit">{{ $t("保存") }}</a-button>
    </template>
  </a-modal>
</template>
<script lang='ts' setup>
import { message } from "ant-design-vue";
import { GenItem, AddItem } from "./item-data";
import {
  queryMenus,
  addRoleMenus,
  GetRoleRouter,
  GetRoleMenus,
} from "@/api/setting";
import { useLanguage } from "@/hooks/index";
import { list2Tree, showCurrentLang } from "@/utils/common/common";
import { permissions } from "@/utils/const";
let spinning = ref(false)
let listData = [];
const { isEn, isCn, isArabic } = useLanguage();
const { t: $t } = useI18n();
const loading = ref(false);
const formRef = ref(null);
const emit = defineEmits(["ok", "close", "update:visible"]);
const menuOptions = permissions;
let currentId = ref(0);
let currentSelectMenu = ref("");
let menuSelected = ref([]);
const spePer = ["viewFlag", "modifyFlag", "removeFlag", "createFlag"];
let totalPermission = reactive({});

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  target: {
    type: Object,
    required: true,
    default: () => { },
  },
});
const open = computed({
  get() {
    return props.visible;
  },
  set(value) {
    emit("update:visible", value);
  },
});
const formState = ref(new GenItem());
const isEdit = computed(() => {
  if (isEmpty(props.target)) return false;
  return true;
});
const treeData = ref([]);
let checkedKeys = ref({
  checked: [],
  halfChecked: [10000004]
});

const getRoles = async () => {
  spinning.value = true
  const { data } = await queryMenus().finally(() => {
    spinning.value = false
  })
  // getSecondMenus(data)
  listData = data ?? [];
  treeData.value = list2Tree(data) ?? [];
};

const getRoleRouter = async (id) => {
  spinning.value = true
  const { data } = await GetRoleRouter(id).finally(() => {
    spinning.value = false
  })
  data.forEach((i) => {
    checkedKeys.value.checked.push(i.id);
  });
  console.log('=checkedKeys.value==========>', checkedKeys.value);

};

const getRoleMenus = async (id) => {
  spinning.value = true
  let list = []
  const { data } = await GetRoleMenus({ roleId: id }).finally(() => {
    spinning.value = false
  })
  let obj = {};
  data.forEach((i) => {
    if (i.menuId) {
      obj[i.menuId] = i?.otherAuth ?? [];
      if (i.viewFlag) obj[i.menuId].push("viewFlag");
      if (i.modifyFlag) obj[i.menuId].push("modifyFlag");
      if (i.removeFlag) obj[i.menuId].push("removeFlag");
      if (i.createFlag) obj[i.menuId].push("createFlag");
    }
    list.push(i.id);
  });
  totalPermission = cloneDeep(obj);
  
};
//勾选框选中
const onCheck = (checkedKeys: any, e: { checked: Boolean, checkedNodes: any, node: any, event: any }) => {
  console.log('所选中的节点====>', checkedKeys, e.checkedNodes, e.node);

}
const setMenuPermission = (parentId, id, nameZh, nameEn, nameAr) => {
  console.log("setMenuPermission:", parentId, id, nameZh, nameEn, nameAr);

  currentSelectMenu.value = isCn.value
    ? nameZh
    : isEn.value
      ? nameEn
      : isArabic.value
        ? nameAr
        : nameEn;
  if (!parentId) {
    currentId.value = 0;
    return;
  }
  // if (!checkedKeys.value.includes(id)) return
  if (id) totalPermission[currentId.value] = cloneDeep(menuSelected.value);
  currentId.value = id;
  menuSelected.value = totalPermission[id];
};
watch(
  () => open,
  (newVal, oldVal) => {
    checkedKeys.value.checked = [];
    totalPermission = {};
    if (newVal.value) {
      getRoles();
      getRoleRouter(props.target.id);
      getRoleMenus(props.target.id);
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
// 根据子级找上级
function findAllParents(tree, childId, parents=[]) {
    for (const node of tree) {
        if (node.id === childId) {
            parents.push(node.id);
            return parents;
        }
        if (node.children?.length > 0) {
            const newParents = [...parents, node.id];
            const foundParents = findAllParents(node.children, childId, newParents);
            if (foundParents.length > 0) {
                return foundParents;
            }
        }
    }
    return [];
}
//选中节点
const fatherNode = ref([]) // 选择子级的父节点的id
const chooseKey = (checked: any, e: any) => {
  console.log('checked', checked)
  console.log('arrList', e)
  let parentId = []
  let arrList = []
  if (e.checked) {
    const childIds = findChildIds(treeData.value, e.node.id);
    console.log(childIds);
    // 父级勾选，就勾选它以下的所有子级
    if (childIds.length > 0) {
      arrList = [...childIds, ...checked.checked]
    } else {
      parentId = findAllParents(treeData.value, e.node.id);
      arrList = [...parentId, ...checked.checked]
      // fatherNode.value = [...new Set(arrList)];
      // checkedKeys.value.checked = fatherNode.value
    }
    fatherNode.value = [...new Set(arrList)];
    checkedKeys.value.checked = fatherNode.value
  } else {
    const childIds = findChildIds(treeData.value, e.node.id);
    console.log(childIds);
    // 父级点取消，就取消它以下的所有子级
    if (childIds.length > 0) {
      checkedKeys.value.checked = checkedKeys.value.checked.filter(item => !childIds.includes(item))
    } else {
      // 过滤取消的节点
      parentId = findAllParents(treeData.value, e.node.id);
      console.log('parentId', parentId)
      checkedKeys.value.checked = checkedKeys.value.checked.filter(item => !parentId.includes(item))
      let list = []
      // 再根据id查是否有父级，父级如果还有子级还是需要显示父级
      checkedKeys.value.checked.forEach(element => {
        const allList = findAllParents(treeData.value, element);
        list.push(...allList)
      });
      fatherNode.value = [...new Set(list)];
      console.log('fatherNode.value', fatherNode.value)
      checkedKeys.value.checked = fatherNode.value
    }
  }
};

// 根据父级找下级
function findChildIds(tree, parentId) {
    const result = [];
    function traverse(node) {
        if (node.id === parentId) {
            addChildrenIds(node.children);
        } else if (Array.isArray(node.children)) {
            node.children.forEach((child) => {
                traverse(child);
            });
        }
    }

    function addChildrenIds(children) {
        if (Array.isArray(children)) {
            children.forEach((child) => {
                result.push(child.id);
                addChildrenIds(child.children);
            });
        }
    }

    traverse({id: 0, children: tree}); // Adding a dummy node to start traversal
    return result;
}

const submit = debounce(async () => {
  if (currentId.value) {
    totalPermission[currentId.value] = menuSelected.value;
  }
  let data = {
    roleId: props.target.id,
    menuList: [],
  };
  console.log('checkedKeys.value====>>>>', checkedKeys.value.checked)
  let arrList = cloneDeep(checkedKeys.value.checked)
  console.log('arrList', arrList)
  console.log('menuSelected.value', menuSelected.value)
  let lists = [];
  arrList.forEach(i => {
    const target = listData.find((k) => i === k.id);
    console.log('target', target)
    if (target.parentId === 0) {
      lists.push({
        menuId: target.id,
        viewFlag: true,
        modifyFlag: true,
        removeFlag: true,
        createFlag: true,
        parentId: 0,
        otherAuth: [],
      })
    } else {
      const obj = {
        menuId: target.id,
        viewFlag: false,
        modifyFlag: false,
        removeFlag: false,
        createFlag: false,
        parentId: target.parentId,
        otherAuth: [],
      };
      const perList = totalPermission[i] ?? [];
      if (perList.includes("viewFlag")) obj.viewFlag = true;
      if (perList.includes("modifyFlag")) obj.modifyFlag = true;
      if (perList.includes("removeFlag")) obj.removeFlag = true;
      if (perList.includes("createFlag")) obj.createFlag = true;
      let newPer = perList.filter((item) => {
        return spePer.every((prop) => {
          return prop !== item;
        });
      });
      obj.otherAuth = newPer;
      lists.push(obj);
    }
  })
  console.log('lists', lists)
  data.menuList = lists;
  if (data.menuList.length === 0) return message.warning($t("至少勾选一条菜单"));
  loading.value = true;
  await addRoleMenus(data).finally(() => {
    loading.value = false;
  });
  message.success($t("操作成功"));
  handleOk();
}, 1000);
//
// 自定义业务处理
//
const handleOk = () => {
  emit("ok", (open.value = false));
};
const handleClose = () => {
  emit("update:visible", false);
};
</script>
<style lang='scss' scoped>
.menus {
  display: flex;
  justify-content: space-between;
  .menus-permission {
    width: 50%;
  }
  :deep(.ant-tree) {
    height: 70vh;
    overflow: hidden;
    overflow-y: scroll;
    min-width: 300px;
    max-width: 50%;
    display: flex;
  }
}
</style>